<?php
/**
 *  * 系统-受国家计算机软件著作权保护 - !
 * =========================================================
 * Copy right 2018-2025 成都海之心科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: http://www.ohyu.cn
 * 这不是一个自由软件！在未得到官方有效许可的前提下禁止对程序代码进行修改和使用。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 * User: ohyueo
 * Date: 2022/3/24
 * Time: 16:01
 */

namespace app\common;
use think\facade\Cache;

class AliYun
{
    /*获取token*/
    public function gettoken(){
        //获取缓存的token
        $token = Cache::get('aliyun_token');
        if($token){
            return $token;
        }
        //通过AccessKey ID和AccessKey Secret获取token
        $accessKeyId = config('-speechsite.spee_appid');
        $accessKeySecret = config('-speechsite.spee_appkey');
        if(!$accessKeyId ||!$accessKeySecret){
            return false;
        }
        $url = 'https://nls-meta.cn-shanghai.aliyuncs.com/token/getToken';
        $token = posturl($url, array('id'=>$accessKeyId, 'secret'=>$accessKeySecret));
        $token = json_decode($token, true);
        if($token['Code'] == '200'){
            //到期时间
            $expire_time = time()-$token['Token']['ExpireTime'];
            //缓存一下token
            Cache::set('aliyun_token', $token['Token']['Id'], $expire_time);
            return $token['Token']['Id'];
        }else{
            return false;
        }
    }
    /**获取阿里云新版Access Token */
    public function accesstoken(){
        //获取缓存的token
        $token = Cache::get('aliyun_token');
        if($token){
            return $token;
        }
        //通过AccessKey ID和AccessKey Secret获取token
        $accessKeyId = config('-speechsite.spee_appid');
        $accessKeySecret = config('-speechsite.spee_appkey');
        if(!$accessKeyId ||!$accessKeySecret){
            return false;
        }
        //通过AccessKey ID和AccessKey Secret获取获取阿里云新版Access Token
        $url="http://nls-meta.cn-shanghai.aliyuncs.com/";
        // 构造请求参数
        $parameters = array(
            'Format' => 'JSON',
            'Version' => '2019-02-28',
            'AccessKeyId' => $accessKeyId,
            'SignatureMethod' => 'HMAC-SHA1',
            'Timestamp' => gmdate('Y-m-d\TH:i:s\Z'),
            'SignatureVersion' => '1.0',
            'SignatureNonce' => $this->uuid(),
            'RegionId'=>'cn-shanghai',
            'Action' => 'CreateToken', // 要调用的API
        );
        // 对参数进行排序
        ksort($parameters);
        // 构造规范化请求字符串
        $canonicalizedQueryString = '';
        foreach ($parameters as $key => $value) {
            $canonicalizedQueryString .= '&' . rawurlencode($key) . '=' . rawurlencode($value);
        }
        $canonicalizedQueryString = substr($canonicalizedQueryString, 1);
        // 构造待签名字符串
        $stringToSign = 'GET&%2F&' . rawurlencode($canonicalizedQueryString);
        // 计算签名
        $signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true));
        // 添加签名到请求参数中
        $parameters['Signature'] = $signature;
        // 构造最终请求URL
        $requestUrl = $url . '?' . http_build_query($parameters);
        // 发送请求
        $response = $this->getreurl($requestUrl);
        $token = json_decode($response, true);
        if(@$token['Token']){
            //到期时间
            $expire_time = time()-$token['Token']['ExpireTime'];
            //缓存一下token
            Cache::set('aliyun_token', $token['Token']['Id'], $expire_time);
            return $token['Token']['Id'];
        }else{
            return false;
        }
    }
    /**
    * Generates an UUID
    *
    * @author Anis uddin Ahmad
    * @param string an optional prefix
    * @return string the formatted uuid
    */
    
    protected function uuid($prefix = '')
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid = substr($chars,0,8) . '-';
        $uuid .= substr($chars,8,4) . '-';
        $uuid .= substr($chars,12,4) . '-';
        $uuid .= substr($chars,16,4) . '-';
        $uuid .= substr($chars,20,12);
        return $prefix . $uuid;
    }
    protected function getreurl($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }
    /*语音合成*/
    public function tts($text, $voice = 'xiaoyun', $format = 'mp3', $sample_rate = '16000', $volume = '50', $speech_rate = '0', $pitch_rate = '0'){
        $accessKeyId = config('-speechsite.spee_appkey2');
        $token = $this->accesstoken();
        if(!$token){
            return false;
        }
        $url = 'https://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/tts';
        $data = array(
            'appkey' => $accessKeyId,
            'token' => $token,
            'text' => $text,
            'format' => $format,
            'voice' => $voice,
            'sample_rate' => $sample_rate,
            'volume' => $volume,
            'speech_rate' => $speech_rate,
            'pitch_rate' => $pitch_rate,
        );
        //$result = posturl($url, $data);
        //$result = json_decode($result, true);
        // 发送GET请求
        $requestUrl = $url . '?' . http_build_query($data);
        $response = @file_get_contents($requestUrl);
        // 获取HTTP响应头
        $httpResponseHeader = $http_response_header;
        // 提取状态码
        preg_match('/\d{3}/', $httpResponseHeader[0], $matches);
        $status_code = $matches[0];
        // 判断状态码是否为200
        if ($status_code == '200') {
            return $response;
            //echo '语音合成成功';
        } else {
            return false;
            //echo '语音合成失败，状态码：' . $status_code;
        }
        // if(@$response['status']){
        //     return $response;
        // }else{
        //     return $response;
        // }
    }
}